package com.xx.jicheng.service.impl;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import com.xx.jicheng.service.ConfigService;
import com.xx.jicheng.service.SmsService;

@Service
public class SmsServiceImpl implements SmsService {

	@Autowired
	@Qualifier("commonRedisTemplate")
	private RedisTemplate<String, Object> template;

	@Override
	public String generateSmsCode(String name, String cellphone) {
		// 4位随机数字验证码
		String code = randomCode(4);
		// 放入缓存，10分钟有效
		template.boundValueOps(ConfigService.REGISTER_PREFIX + cellphone).set(code, 10, TimeUnit.MINUTES);
		// 发送短信，测试时可以注释掉
//		sendSms(name, code, cellphone);
		return code;
	}

	@Override
	public boolean validateSmsCode(String cellphone, String vercode) {
		Object ocode = template.boundValueOps(ConfigService.REGISTER_PREFIX + cellphone).get();
		if (ocode == null) {
			return false;
		} 
		return ocode.equals(vercode);
	}
	
	@Override
	public void clearSmsCode(String cellphone) {
		template.delete(ConfigService.REGISTER_PREFIX + cellphone);
	}

	private String randomCode(int n) {
		StringBuilder sb = new StringBuilder(n);
		Random r = new Random();
		for (int i = 0; i < n; i++) {
			sb.append(r.nextInt(10));
		}
		return sb.toString();
	}

	private void sendSms(String name, String code, String cellphone) {
		try {
			TaobaoClient client = new DefaultTaobaoClient(
					"http://gw.api.taobao.com/router/rest", "23543058",
					"d7b81e8cc7615dbc1b296ef803d2a039");
			AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
			req.setExtend("");
			req.setSmsType("normal");
			req.setSmsFreeSignName("个人测试");
			req.setSmsParamString("{\"name\":\"" + name + "\", \"code\":\"" + code + "\"}");
			req.setRecNum(cellphone);
			req.setSmsTemplateCode("SMS_27925082");
			AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
			System.out.println(rsp.getBody());
//			System.out.println(rsp.getErrorCode().equals("0"));
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
